class Solution {
    public int minFallingPathSum(int[][] matrix) {
        //1.创建dp表
        //2.初始化
        //3.填表
        //4.返回值

        int m = matrix.length+1;
        int n = matrix[0].length+2;
        int[][] dp = new int[m][n];

        //初始化第第一列和最后一列
        for(int i = 1; i < m; i++) {
            dp[i][0] = Integer.MAX_VALUE;;
            dp[i][n-1] = Integer.MAX_VALUE;;
        }

        for(int i = 1; i < m; i++) {
            for(int j = 1; j < n-1; j++) {
                dp[i][j] = Math.min(Math.min(dp[i-1][j-1], dp[i-1][j]), dp[i-1][j+1]) + matrix[i-1][j-1];
            }
        }

        int minSum = dp[m-1][1];
        for(int i = 2; i < n-1; i++) {
            if(minSum > dp[m-1][i]) {
                minSum = dp[m-1][i];
            }
        }
        return minSum;
    }
}